﻿using Hidistro.Core;
using Hidistro.Entities;
using Hidistro.Entities.Orders;
using Hidistro.Entities.Sales;
using Hidistro.Membership.Context;
using Hidistro.Membership.Core;
using Hidistro.SaleSystem.Shopping;
using Hidistro.UI.Common.Controls;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using wnxd.javascript;

namespace Hidistro.UI.SaleSystem.Tags
{
    public class wnxd_SpreadPageOrder_Phone : AscxTemplatedWebControl
    {
        private string[] _pids = new string[] { };
        private string[] _names = new string[] { };
        private string[] _skus = new string[] { };
        public string[] _prices = new string[] { };
        public HtmlGenericControl ul_pid_list;
        public Literal l_sku_list;
        protected override void OnLoad(EventArgs e)
        {
            this.EnsureChildControls();
        }
        protected override void AttachChildControls()
        {
            this.ul_pid_list = (HtmlGenericControl)this.FindControl("pid_list");
            this.l_sku_list = (Literal)this.FindControl("sku_list");
            if (!this.Page.IsPostBack)
            {
                if (this._names.Length == 0)
                {
                    this._pids = this._pids.OrderBy(x => x).ToArray();
                    DataTable dt = this.GetDataTable("select ProductName from Hishop_Products where ProductId in (" + this.Pids + ") order by ProductId");
                    IList<string> l = new List<string>();
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        l.Add(dt.Rows[i]["ProductName"].ToString());
                    }
                    this._names = l.ToArray();
                }
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("<li class=\"xuanz\" pid=\"{0}\"><a href=\"javascript:void(0);\">{1}</a></li>", this._pids[0], this._names[0]);
                for (int i = 1; i < this._pids.Length; i++)
                {
                    sb.AppendFormat("<li pid=\"{0}\"><a href=\"javascript:void(0);\">{1}</a></li>", this._pids[i], this._names[i]);
                }
                this.ul_pid_list.InnerHtml = sb.ToString();
                if (this._prices.Length == 0)
                {
                    this._skus = this._skus.OrderBy(x => x).ToArray();
                    string sql = "select SalePrice from Hishop_SKUs where ProductId = " + this._pids[0] + " and (";
                    for (int i = 0; i < this._skus.Length; i++)
                    {
                        if (i > 0) sql += " or ";
                        sql += "SkuId = '" + this._pids[0] + "_" + this._skus[i] + "'";
                    }
                    sql += ") order by SkuId";
                    DataTable dt = this.GetDataTable(sql);
                    IList<string> l = new List<string>();
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        l.Add(((decimal)dt.Rows[i]["SalePrice"]).ToString("F0"));
                    }
                    this._prices = l.ToArray();
                }
                DataTable table = this.GetDataTable("select ValueStr from Hishop_AttributeValues where ValueId in (" + this.Skus + ")");
                sb = new StringBuilder();
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    sb.Append("<div class=\"thn\" style=\"white-space: nowrap; line-height: 20px; margin-top: 5px;\"><label>");
                    sb.AppendFormat("<p><input class=\"dxk\" type=\"radio\" price=\"{0}\" name=\"sku\" value=\"{1}\"{3}>{2}</p>", this._prices[i], i, table.Rows[i]["ValueStr"], i > 0 ? "" : " checked=\"checked\"");
                    sb.Append("<p style=\"padding-left: 15px; padding-top: 0.5em;\"></p>");
                    sb.AppendFormat("<p style=\"margin-left: 15px;\"><span class=\"sj1\" style=\"color: #F00\">售 价：￥{0}</span></p>", this._prices[i]);
                    sb.Append("</label></div>");
                }
                this.l_sku_list.Text = sb.ToString();
            }
        }
        protected override void OnInit(EventArgs e)
        {
            if (this.SkinName == null)
            {
                this.SkinName = "/ascx/tags/wnxd_SpreadPageOrder_Phone_Common.ascx";
            }
            base.OnInit(e);
        }
        protected json Submit()
        {
            json json = new json(new { error = -1 });
            try
            {
                int region;
                if (!int.TryParse(this.Page.Request.Form["regionSelectorValue"], out region) || region == 0)
                {
                    json["msg"] = "请选择收货地址";
                    return json;
                }
                string pattern = @"[\u4e00-\u9fa5a-zA-Z]+[\u4e00-\u9fa5_a-zA-Z0-9]*";
                Regex regex = new Regex(pattern);
                if (!(!string.IsNullOrEmpty(this.Page.Request.Form["shr"]) && regex.IsMatch(this.Page.Request.Form["shr"])))
                {
                    json["msg"] = "请输入正确的收货人姓名";
                    return json;
                }
                if ((this.Page.Request.Form["shr"].Length < 2) || (this.Page.Request.Form["shr"].Length > 20))
                {
                    json["msg"] = "收货人姓名长度应在2-20个字符之间";
                    return json;
                }
                if (string.IsNullOrEmpty(this.Page.Request.Form["shdz"]))
                {
                    json["msg"] = "请输入收货人详细地址";
                    return json;
                }
                if (string.IsNullOrEmpty(this.Page.Request.Form["sjhm"]))
                {
                    json["msg"] = "请输入正确的手机号码";
                    return json;
                }
                int pid;
                if (!int.TryParse(this.Page.Request.Form["pid"], out pid) || pid < 0 || pid >= _pids.Length)
                {
                    json["msg"] = "请选择要购买的商品";
                    return json;
                }
                int sku;
                if (!int.TryParse(this.Page.Request.Form["sku"], out sku) || sku < 0 || sku >= _skus.Length)
                {
                    json["msg"] = "请选择要购买的商品";
                    return json;
                }
                string SkuId = string.Empty;
                if (!string.IsNullOrEmpty(this.Page.Request.Form["sgerg"]))
                {
                    SkuId = _pids[pid] + "_" +this.Page.Request.Form["sgerg"].ToString()+"_"+ _skus[sku];
                }
                else
                {
                    SkuId = _pids[pid] + "_" + _skus[sku];
                }
                ShoppingCartInfo shoppingCart = ShoppingCartProcessor.GetShoppingCart(SkuId, 1, true);
                if (shoppingCart == null)
                {
                    json["msg"] = "请选择要购买的商品";
                    return json;
                }
                if (_prices.Length > 0)
                {
                    shoppingCart.LineItems[0].AdjustedPrice = decimal.Parse(_prices[sku]);
                }
                if (this.Page.Request.Form["fkfs"] != "1")
                {
                    shoppingCart.ReducedPromotionAmount = shoppingCart.LineItems[0].AdjustedPrice * 0.08m;
                    shoppingCart.IsReduced = true;
                }
                OrderInfo orderInfo = GetOrderInfo(shoppingCart);

                string source = null;
                System.Web.HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies["Source"];
                if (cookie != null) source = cookie.Value;
                else
                    source = this.Page.Request.Form["source"];
                if (ShoppingProcessor.CreatOrder(orderInfo, source))
                {
                    orderInfo.OnCreated();
                    json["error"] = 0;
                    json["url"] = "/Vshop/FinishOrder.aspx?orderId=" + orderInfo.OrderId;
                }
                else
                {
                    json["msg"] = "购买失败";
                }
            }
            catch
            {
                json["msg"] = "未知错误";
            }
            return json;
        }
        private OrderInfo GetOrderInfo(ShoppingCartInfo shoppingCartInfo)
        {
            OrderInfo orderInfo = ShoppingProcessor.ConvertShoppingCartToOrder(shoppingCartInfo, false, false, true);
            if (orderInfo == null)
            {
                return null;
            }
            orderInfo.OrderId = this.GenerateOrderId();
            orderInfo.OrderDate = DateTime.Now;
            IUser user = HiContext.Current.User;
            orderInfo.UserId = user.UserId;
            orderInfo.Username = user.Username;
            orderInfo.OrderStatus = OrderStatus.WaitBuyerPay;
            orderInfo.RefundStatus = RefundStatus.None;
            FillOrderShippingMode(orderInfo, shoppingCartInfo);
            FillOrderPaymentMode(orderInfo);
            orderInfo.OrderSource = OrderSource.Wap;
            return orderInfo;
        }
        private void FillOrderShippingMode(OrderInfo orderInfo, ShoppingCartInfo shoppingCartInfo)
        {
            orderInfo.Address = Globals.HtmlEncode(this.Page.Request.Form["shdz"]);
            orderInfo.ShipTo = Globals.HtmlEncode(this.Page.Request.Form["shr"]);
            orderInfo.CellPhone = this.Page.Request.Form["sjhm"];
            orderInfo.ShippingModeId = int.Parse("2", NumberStyles.None);
            int region;
            if (int.TryParse(this.Page.Request.Form["regionSelectorValue"], out region))
            {
                orderInfo.RegionId = region;
                orderInfo.ShippingRegion = RegionHelper.GetFullRegion(region, "，");
            }
            orderInfo.ShipToDate = "时间不限";
            ShippingModeInfo shippingMode = ShoppingProcessor.GetShippingMode(orderInfo.ShippingModeId, true);
            if (shippingMode != null)
            {
                orderInfo.ShippingModeId = shippingMode.ModeId;
                orderInfo.ModeName = shippingMode.Name;
                if (!(shoppingCartInfo.IsFreightFree || ((shoppingCartInfo.LineItems.Count<ShoppingCartItemInfo>(a => !a.IsfreeShipping) <= 0) && (shoppingCartInfo.LineGifts.Count <= 0))))
                {
                    orderInfo.AdjustedFreight = orderInfo.Freight = ShoppingProcessor.CalcFreight(orderInfo.RegionId, shoppingCartInfo.Weight, shippingMode);
                }
                else
                {
                    orderInfo.AdjustedFreight = orderInfo.Freight = 0M;
                }
            }
        }
        private void FillOrderPaymentMode(OrderInfo orderInfo)
        {
            orderInfo.PaymentTypeId = int.Parse(this.Page.Request.Form["fkfs"]);
            PaymentModeInfo paymentMode = ShoppingProcessor.GetPaymentMode(orderInfo.PaymentTypeId);
            if (paymentMode != null)
            {
                orderInfo.PaymentType = Globals.HtmlEncode(paymentMode.Name);
                orderInfo.PayCharge = ShoppingProcessor.CalcPayCharge(orderInfo.GetTotal(), paymentMode);
                orderInfo.Gateway = paymentMode.Gateway;
            }
        }
        private string GenerateOrderId()
        {
            string str = string.Empty;
            Random random = new Random();
            for (int i = 0; i < 7; i++)
            {
                int num = random.Next();
                str = str + ((char)(0x30 + ((ushort)(num % 10)))).ToString();
            }
            int v = random.Next(0, 9);
            return (DateTime.Now.ToString("yyyyMMdd") + str + v);
        } 
        public string Pids
        {
            get
            {
                return string.Join(",", _pids);
            }
            set
            {
                _pids = value.Split(',');
            }
        }
        public string Names
        {
            get
            {
                return string.Join(",", _names);
            }
            set
            {
                _names = value.Split(',');
            }
        }
        public string Skus
        {
            get
            {
                return string.Join(",", _skus);
            }
            set
            {
                _skus = value.Split(',');
            }
        }
        public string Prices
        {
            get
            {
                return string.Join(",", _prices);
            }
            set
            {
                _prices = value.Split(',');
            }
        }
        private Database database = DatabaseFactory.CreateDatabase();
        private DataTable GetDataTable(string sql)
        {
            DbCommand cmd = database.GetSqlStringCommand(sql);
            DataTable dt;
            using (IDataReader reader = database.ExecuteReader(cmd))
            {
                dt = DataHelper.ConverDataReaderToDataTable(reader);
            }
            return dt;
        }
        private DataTable[] GetDataTables(string sql)
        {
            DbCommand cmd = database.GetSqlStringCommand(sql);
            IList<DataTable> dts = new List<DataTable>();
            using (IDataReader reader = database.ExecuteReader(cmd))
            {
                do
                {
                    dts.Add(DataHelper.ConverDataReaderToDataTable(reader));
                }
                while (reader.NextResult());
            }
            return dts.ToArray();
        }
    }
}
